<?php

namespace app\user\model;

use app\common\controller\GlobalVariable;
use think\Db;
use think\Model;
use think\Request;
use think\Session;

class User extends Model
{
    public function isRegister($name)
    {
        $data = Db::table('xwd_user_account')->where(['account' => $name])->find();
        if ($data) {
            return true;
        }
        return false;
    }

    /**
     * @param $pid 用户名
     * @param $sid 密码
     * @return bool
     * 用户登录，Session
     */

    public function doLogin($nid, $pid)
    {
        $find = Db::table('xwd_user_account')->where('account', $nid)->find();
        $salt = $find["salt"];
        $password = md5($pid . $salt);
        $validate = [
            'account' => $nid,
            'password' => $password,
        ];
        $data = Db::table('xwd_user_account')->where($validate)->find();
        $data['user_id'] = json_encode($data['user_id']);
        if ($data) {
            Session::set('user_id', $data['user_id'], 'xwd_user');
            $time = time();
//            var_dump($time);
            Session::set('expiration_date', $time + 43200);
            $expire_time = $time + 43200;
            $token = Request::instance()->token();
            $array = [
                'user_id' => $data['user_id'],
                'ip' => GlobalVariable::get_client_ip(),
                'in_time' => date('Y-m-d H:i:s'),
                'token' => $token,
                'expire_time' => $expire_time,
            ];
            Db::name('xwd_user_login_info')->insert($array);
//            var_dump($data['user_id']);
            return GlobalVariable::promptData(['token' => $token, 'expire_time' => $expire_time]);
        } else {
            return GlobalVariable::promptErrorByJSON("错误", 401, "账号或密码错误！");
        }
    }

    /**
     * 用户注销,Session
     */
    public function doLogout()
    {
        $token = Request::instance()->header('token');
        $select = Db::name('xwd_user_login_info')->where('token', $token)->find();
        $in_time = $select["in_time"];
        $out_time = date('Y-m-d H:i:s');
        $in_time_s = strtotime($in_time);
        $out_time_s = strtotime($out_time);
        $time_long = $out_time_s - $in_time_s;
        Db::table('xwd_user_login_info')->where('token', $token)->update(['out_time' => $out_time, 'time_long' => $time_long, 'out_c' => $out_time_s]);
        Session::clear('xwd_user');
        return true;
    }

    /**
     * 用户注册
     */
    public function doRegister($nid, $pid, $nickname, $researcher_id, $is_author, $orcid, $identity, $institution, $department, $author_id, $email, $phoneNum, $headImg)
    {
        $salt = $this->CreateSalt();
        $username = "";
        $password = md5($pid . $salt);
        $data = [
            'account' => $nid,
            'password' => $password,
            'salt' => $salt,
            'nickname' => $nickname,
            'create_time' => date('Y-m-d H:i:s'),
        ];
//        $this->encryption($pid),
        $isRegister = $this->isRegister($nid);
        if (!$isRegister) {
//            $this->save($data);
            if ($is_author == 1) {
                Db::table('xwd_user_account')->insert($data);
                $find = Db::table('xwd_user_account')->where('account', $nid)->find();
                $user_id = $find["user_id"];
                Db::table('xwd_author_info')->insert(['researcher_id' => $researcher_id]);
                $find2 = Db::table('xwd_author_info')->where('researcher_id', $researcher_id)->find();
                $author_id = $find2["author_id"];
                Db::table('xwd_user_info')->insert(['user_id' => $user_id, 'username' => $username, 'researcher_id' => $researcher_id, 'is_author' => $is_author, 'author_id' => $author_id, 'orcid' => $orcid, 'identity' => $identity, 'institution' => $institution, 'department' => $department, 'author_id' => $author_id, 'email' => $email, 'phoneNum' => $phoneNum, 'headImg' => $headImg]);
                return true;
            } else {
                Db::table('xwd_user_account')->insert($data);
                $find = Db::table('xwd_user_account')->where('account', $nid)->find();
                $user_id = $find["user_id"];
                Db::table('xwd_user_info')->insert(['user_id' => $user_id, 'username' => $username, 'researcher_id' => $researcher_id, 'is_author' => $is_author, 'author_id' => $author_id, 'orcid' => $orcid, 'identity' => $identity, 'institution' => $institution, 'department' => $department, 'author_id' => "", 'email' => $email, 'phoneNum' => $phoneNum, 'headImg' => $headImg]);
                return true;
            }
        }
        return false;
    }

    /**
     * 设置用户信息
     * @return string
     */

    public
    function setInfo($array, $token)
    {
        $this->checkAllowField($array);
        $findu = Db::table('xwd_user_login_info')->where('token', $token)->find();
        $user_id = json_encode($findu['user_id']);
        if (isset($array['researcher_id'])) {
            $flag = Db::table('xwd_user_info')->where(['researcher_id' => $array['researcher_id']])->find();
            if ($flag != null) {
                return GlobalVariable::promptErrorByJSON("错误", 500, "ResearcherID已经被注册!");
            }
        }
        if (isset($array['orcid'])) {
            $flag = Db::table('xwd_user_info')->where(['orcid' => $array['orcid']])->find();
            if ($flag != null) {
                return GlobalVariable::promptErrorByJSON("错误", 500, "ORCID已经被注册!");
            }
        }
        if (isset($array['phoneNum'])) {
            $flag = Db::table('xwd_user_info')->where(['phoneNum' => $array['phoneNum']])->find();
            if ($flag != null) {
                return GlobalVariable::promptErrorByJSON("错误", 500, "手机号已经被注册!");
            }
        }
        if (isset($array['email'])) {
            $flag = Db::table('xwd_user_info')->where(['email' => $array['email']])->find();
            if ($flag != null) {
                return GlobalVariable::promptErrorByJSON("错误", 500, "邮箱已经被注册!");
            }
        }
        $find = Db::table('xwd_user_login_info')->where('token', $token)->find();
        $findA = Db::table('xwd_user_info')->where('user_id', $find['user_id'])->find();
        $author_id = json_encode($findA['author_id']);
//        var_dump($author_id);
        if ($author_id == '0') {
            $author = ['researcher_id' => $array['researcher_id'], 'orcid' => $array['orcid']];
            Db::table('xwd_author_info')->insert($author);
            $findB = Db::table('xwd_author_info')->where('researcher_id', $array['researcher_id'])->find();
            $author_id = json_encode($findB['author_id']);
            Db::table('xwd_user_info')->where(['user_id' => $user_id])->update(['is_author' => 1, 'author_id' => $author_id]);
        }
        Db::table('xwd_user_info')->where(['user_id' => $user_id])->update($array);
        unset($array['phoneNum']);
        unset($array['email']);
        unset($array['headImg']);
        unset($array['user_id']);
        if (isset($array['username'])) {
            $authorname = $array['username'];
            $array['authorname'] = $authorname;
            unset($array['username']);
        }
        Db::table('xwd_author_info')->where('author_id', $author_id)->update($array);
        return true;
    }

    protected
    function encryption($string, $salt)
    {
        $pwd = sha1($string . $salt);
        return md5($pwd);
    }

//    全献文帝最大的盐产商
    protected
    function CreateSalt()
    {
        $str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890';
        $randStr = str_shuffle($str);//打乱字符串
        $salt = substr($randStr, 0, 6);//substr(string,start,length);返回字符串的一部分
        return $salt;
    }

    public
    function updatePwd($original, $change)
    {
        settype($original, 'string');
        settype($change, 'string');
        $userid = Db::table('xwd_user_login_info')->where(['token' => Request::instance()->header('token')])->find();
//        var_dump($userid);
        $userData = Db::table('xwd_user_account')->where('user_id', json_encode($userid['user_id']))->find();
        $salt = $userData['salt'];
        if ($userData['password'] == md5($original . $salt)) {
            if (strlen($change) < 6) {
                return GlobalVariable::promptErrorByJSON("错误", 406, "密码应大于六位！");
            }
            Db::table('xwd_user_account')->where('user_id', json_encode($userid['user_id']))->update(['password' => md5($change . $salt)]);
            return GlobalVariable::promptOkStatus();
        }
        return GlobalVariable::promptErrorByJSON("错误", 401, "原密码错误!");
    }
}